package cn.edu.stu.syllabus.oa.star;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.edu.stu.syllabus.R;
import cn.edu.stu.syllabus.adapters.OaAdapter;
import cn.edu.stu.syllabus.base.BaseFragment;
import cn.edu.stu.syllabus.base.BaseQuickClickAdapter;
import cn.edu.stu.syllabus.base.StoreProxy;
import cn.edu.stu.syllabus.repository.oa.local.OaInfoEntry;
import cn.edu.stu.syllabus.oa.detail.OaDetailActivity;
import cn.edu.stu.syllabus.utils.RecyclerPaddingUtils;
import cn.edu.stu.syllabus.utils.ListUtils;
import cn.edu.stu.syllabus.widgets.CustomLoadMoreView;
import cn.edu.stu.syllabus.widgets.DividerItemDecoration;
import cn.edu.stu.syllabus.widgets.CustomLayoutManger;

import static cn.edu.stu.syllabus.utils.NullPointerUtils.checkNotNull;

/**
 * Created by daidaijie on 2017/3/21.
 */

public class OaStarFragment extends BaseFragment implements OaStarContract.View, BaseQuickAdapter.RequestLoadMoreListener {

    OaStarContract.Presenter mPresenter;

    private final int REQUEST_OPEN_DETAIL = 200;

    @BindView(R.id.oaStarRecyclerView)
    RecyclerView mOaStarRecyclerView;

    OaAdapter mOaAdapter;

    View mEmptyView;
    View mErrorView;

    int lastOpenPosition = -1;

    private boolean mRecyclerViewClickable;

    public static OaStarFragment newInstance() {
        OaStarFragment oaStarFragment = new OaStarFragment();
        return oaStarFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_oa_star;
    }

    @Override
    protected void init(Bundle savedInstanceState) {

        CustomLayoutManger customLayoutManger
                = new CustomLayoutManger(mActivity);
        customLayoutManger.setSpeedFast();
        mOaStarRecyclerView.setLayoutManager(customLayoutManger);

        Drawable decLineDrawable = ContextCompat.getDrawable(mActivity, R.drawable.dev_line);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(
                mActivity, DividerItemDecoration.VERTICAL_LIST, decLineDrawable);
        itemDecoration.setHeight(1);
        mOaStarRecyclerView.addItemDecoration(itemDecoration);

        mOaAdapter = new OaAdapter(new ArrayList<OaInfoEntry>());
        mOaAdapter.setLoadMoreView(new CustomLoadMoreView());
        mOaStarRecyclerView.setAdapter(mOaAdapter);

        final String[] items = {"取消收藏"};

        mRecyclerViewClickable = true;
        mOaAdapter.setOnLoadMoreListener(this);
        mOaAdapter.setOnItemClickListener(new BaseQuickClickAdapter.OnItemClickListener<OaInfoEntry>() {
            @Override
            public void onItemClick(OaInfoEntry oaInfoEntry, int position) {
                if (!mRecyclerViewClickable) {
                    return;
                }
                lastOpenPosition = position;
                Intent intent = OaDetailActivity.newIntent(mActivity, oaInfoEntry);
                OaStarFragment.this.startActivityForResult(intent, REQUEST_OPEN_DETAIL);
            }
        });

        mOaAdapter.setOnItemLongClickListener(new BaseQuickClickAdapter.OnItemLongClickListener<OaInfoEntry>() {
            @Override
            public boolean onItemLongClick(final OaInfoEntry oaInfoEntry, final int position) {
                if (!mRecyclerViewClickable) {
                    return false;
                }
                final AlertDialog alertDialog = new AlertDialog.Builder(mActivity)
                        .setTitle("请选择操作")
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    mPresenter.unstarOaInfo(oaInfoEntry, position);
                                }
                            }
                        })
                        .create();
                alertDialog.show();
                return true;
            }
        });

        RecyclerPaddingUtils.fitRecyclerViewPadding(mActivity, mOaStarRecyclerView);

        mEmptyView = LayoutInflater.from(mActivity).inflate(R.layout.empty_view
                , (ViewGroup) mOaStarRecyclerView.getParent(), false);
        mErrorView = LayoutInflater.from(mActivity).inflate(R.layout.error_view
                , (ViewGroup) mOaStarRecyclerView.getParent(), false);
        TextView emptyTextView = (TextView) mEmptyView.findViewById(R.id.emptyTextView);
        emptyTextView.setText("目前还没有收藏，快去添加吧");

        TextView errorTextView = (TextView) mErrorView.findViewById(R.id.errTextView);
        errorTextView.setText("加载失败，请点击重试");
        mErrorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoadMoreRequested();
            }
        });

        StoreProxy.onRestoreInstanceState(savedInstanceState, mPresenter);
        mPresenter.subscribe();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        StoreProxy.onSaveInstanceState(outState, mPresenter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_OPEN_DETAIL
                && resultCode == OaDetailActivity.RESULT_STAR_STATE_CHANGE) {
            boolean isStar = data.getBooleanExtra(OaDetailActivity.EXTRA_IS_STAR, false);
            if (isStar) {
                movePositionToTop(lastOpenPosition);
            } else {
                removeUnstarOaInfo(lastOpenPosition);
            }
        }
    }

    private void movePositionToTop(int position) {
        mRecyclerViewClickable = false;
        mOaAdapter.movePositionToTop(position);
        mRecyclerViewClickable = true;
    }

    @Override
    public void removeUnstarOaInfo(int position) {
        if (position == -1) {
            return;
        }
        mRecyclerViewClickable = false;
        mOaAdapter.remove(position);
        if (ListUtils.getListSizeSafety(mOaAdapter.getData()) == 0) {
            mOaAdapter.setEmptyView(mEmptyView);
        }
        mRecyclerViewClickable = true;
    }

    @Override
    public void setPresenter(OaStarContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }

    @Override
    public void onLoadMoreRequested() {
        mPresenter.loadStarOaEntries();
    }

    @Override
    public void showDataEmpty() {
        mOaAdapter.setEmptyView(mEmptyView);
    }

    @Override
    public void showDataError() {
        mOaAdapter.setEmptyView(mErrorView);
    }

    @Override
    public void setOaInfoList(List<OaInfoEntry> oaInfoEntries) {
        mOaAdapter.setNewData(oaInfoEntries);
    }

    @Override
    public void appendOaInfoList(List<OaInfoEntry> oaInfoEntries) {
        mOaAdapter.addData(oaInfoEntries);
        mOaAdapter.loadMoreComplete();
    }

    @Override
    public void showLoadingFail() {
        mOaAdapter.loadMoreFail();
    }

    @Override
    public void showLoadingEnd() {
        mOaAdapter.loadMoreEnd();
    }

    @Override
    public void onDestroyView() {
        mPresenter.unsubscribe();
        super.onDestroyView();
    }
}
